<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>系统用户列表</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <link rel="stylesheet" href="/resources/layui/css/layui.css" media="all"/>
    <link rel="stylesheet" href="/resources/css/public.css" media="all"/>
    <link rel="stylesheet" href="/resources/dtree/dtree.css">
    <link rel="stylesheet" href="/resources/dtree/font/dtreefont.css">
</head>
<body class="childrenBody">
<blockquote class="layui-elem-quote quoteBox">
    <form class="layui-form" method="post" id="searchFrm">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">所属部门:</label>
                <div class="layui-input-inline">
                    <ul id="searchDeptTree" class="dtree" data-id="0"></ul>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">用户名称:</label>
                <div class="layui-input-inline">
                    <input type="text" name="name" placeholder="请输入用户名称" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">用户地址:</label>
                <div class="layui-input-inline">
                    <input type="text" name="address" placeholder="请输入用户地址" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <button type="button" class="layui-btn" id="doSearch"><span class='layui-icon'>&#xe615;</span>搜索
                </button>
                <button type="reset" id="searchFrmReset" class="layui-btn layui-btn-danger"><span class='layui-icon'>&#xe669;</span>重置
                </button>
            </div>
        </div>
    </form>
</blockquote>
<table id="userTable" class="layui-table" lay-filter="userTable"></table>
<!--表头-->
<div id="userTableToolBar" style="display: none;">
    <a class="layui-btn layui-btn-sm ToolBar" rel="add"><span class="layui-icon">&#xe61f;</span>添加</a>
    <a class="layui-btn layui-btn-sm layui-btn-danger ToolBar" rel="batchdel"><span class="layui-icon">&#xe640;</span>批量删除</a>
    <a class="layui-btn layui-btn-sm layui-btn-blue ToolBar" rel="exprot"><span class="layui-icon">&#xe66d;</span>导出</a>
</div>
<!--操作-->
<div id="userTableRowBar" style="display: none;">
    <a class="layui-btn layui-btn-xs" lay-event="update"><span class="layui-icon">&#xe642;</span>编辑</a>
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><span class="layui-icon">&#xe640;</span>删除</a>
    <a class="layui-btn layui-btn-xs" lay-event="resetUserPwd"><span class="layui-icon">&#xe642;</span>重置密码</a>
    <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="selectUserPermission"><span
            class="layui-icon">&#xe60b;</span>分配角色</a>
</div>

<!-- 添加和修改的弹出层开始 -->
<div style="display: none;padding: 3px" id="saveOrUpdateDiv">
    <form id="dataFrm" lay-filter="dataFrm" class="layui-form layui-form-pane">
        <input type="hidden" class="subType">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">所属部门:</label>
                <div class="layui-input-inline">
                    <input type="hidden" name="id">
                    <ul id="deptTree" class="dtree" data-id="0"></ul>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">排序码:</label>
                <div class="layui-input-inline">
                    <input type="text" name="ordernum" id="ordernum" lay-verify="required" autocomplete="off"
                           placeholder="请输入用户标题" class="layui-input">
                </div>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">领导部门:</label>
                <div class="layui-input-inline">
                    <ul id="leaderDeptTree" class="dtree" data-id="0" ></ul>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">直属领导:</label>
                <div class="layui-input-inline">
                    <select name="mgr" id="mgr"></select>
                </div>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">用户名称:</label>
            <div class="layui-input-inline">
                <input type="text" name="name" lay-verify="required" autocomplete="off" placeholder="请输入用户标题"
                       class="layui-input">
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">登陆名称:</label>
                <div class="layui-input-inline">
                    <input type="text" name="loginname" id="loginname" lay-verify="required" autocomplete="off" placeholder="请输入登陆名称" class="layui-input">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户地址:</label>
            <div class="layui-input-block">
                <input type="hidden" name="id">
                <input type="text" name="address"  autocomplete="off" placeholder="请输入用户标题" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户备注:</label>
            <div class="layui-input-block">
                <textarea class="layui-textarea" name="remark"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">用户性别:</label>
                <div class="layui-input-inline">
                    <input type="radio" name="sex" value="1" title="男" checked="">
                    <input type="radio" name="sex" value="0" title="女">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">是否可用:</label>
                <div class="layui-input-inline">
                    <input type="radio" name="available" value="1" title="可用" checked="">
                    <input type="radio" name="available" value="0" title="不可用">
                </div>
            </div>
        </div>
        <div class="layui-form-item" style="text-align: center;">
            <button type="button" class="layui-btn" lay-filter="doSubmit" lay-submit=""><span class='layui-icon'>&#xe609;</span>提交
            </button>
            <button type="reset" class="layui-btn layui-btn-danger"><span class='layui-icon'>&#xe669;</span>重置</button>
        </div>
    </form>
</div>
<!-- 添加和修改的弹出层结束 -->

<!-- 用户分配角色的弹出层开始 -->
<div id="selectUserRoleDiv" style="display: none;">
    <table id="roleTable" class="layui-table" lay-filter="roleTable"></table>
</div>
<!-- 用户分配角色的弹出层结束 -->

<script type="text/javascript" src="/resources/layui/layui.js"></script>
<script type="text/javascript">
    layui.extend({
        dtree: '/resources/layui_ext/dtree/dtree'
    }).use(['table', 'form', 'layer', 'jquery', 'dtree'], function () {
        var table = layui.table;
        var form = layui.form;
        var layer = layui.layer;
        var $ = layui.jquery;
        var dtree = layui.dtree;

        // //渲染数据表格
        var tableIns = table.render({
            elem: '#userTable'
            , url: '/user/getUserList'
            , toolbar: '#userTableToolBar' //开启头部工具栏，并为其绑定左侧模板
            , defaultToolbar: ['filter', 'print']
            , title: '用户数据表'
            , height: 'full-150'
            , cols: [ [
                {type: 'checkbox', fixed: 'left'}
                , {field: 'id', title: 'ID', align: 'center', fixed: 'left', width: '80'}
                , {field: 'name', title: '用户姓名', align: 'center', width: '150'}
                , {field: 'loginname', title: '登陆名', align: 'center', width: '150'}
                , {field: 'deptName', title: '所属部门', align: 'center', width: '150'}
                , {field: 'bossName', title: '直属领导', align: 'center', width: '150'}
                , {field: 'address', title: '用户地址', align: 'center', width: '150'}
                , {field: 'hiredate', title: '入职时间', align: 'center', width: '150'}
                , {
                    field: 'sex', title: '性别', align: 'center', width: '150', templet: function (d) {
                        return d.sex == 1 ? '<font color=blue>男</font>' : '<font color=red>女</font>';
                    }
                }
                , {
                    field: 'available', title: '是否可用', align: 'center', width: '150', templet: function (d) {
                        return d.available == 1 ? '<font color=blue>可用</font>' : '<font color=red>不可用</font>';
                    }
                }
                , {field: 'remark', title: '用户备注', align: 'center', width: '150'}
                , {field: 'ordernum', title: '排序码', align: 'center', width: '150'}
                , {field: 'imgpath', title: '用户头像', align: 'center', width: '250'}
                , {fixed: 'right', title: '操作', toolbar: '#userTableRowBar', align: 'center', width: '400'}
            ] ]
            , page: true
        });
        //模糊查询
        $("#doSearch").click(function () {
            var params = $("#searchFrm").serialize();
            tableIns.reload({
                url: '/user/getUserList?' + params
            })
        });

        //监听表头按钮的事件
        //监听表头按钮的事件
        $(".childrenBody").on("click", '.ToolBar', function () {
            switch ($(this).attr("rel")) {
                case 'add':
                    $(".subType").val("add");
                    openAddLayer();
                    break;
                case 'batchdel':
                    batchDelete(obj);
                    break;
                case 'exprot':
                    exportUser()
                    break;
            }
            ;
        });

        //监听行按钮的事件
        table.on('tool(userTable)', function(obj){
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            if(layEvent === 'update'){ //修改
                 $(".subType").val("update");
                openUpdateLayer(data);
            } else if(layEvent === 'del'){ //删除
                layer.confirm('真的删除行么', function(index){
                    //obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    layer.close(index);
                    //向服务端发送删除指令
                    $.post("/user/deleteUser",{uid:data.id},function(obj){
                        if(obj.code==200){
                            tableIns.reload();//重载表格
                        }
                        layer.msg(obj.msg);
                    })
                });
            }else if(layEvent==='selectUserPermission'){
                openSelectUserRoleLayer(data);
            }else if(layEvent ==="resetUserPwd"){
                layer.confirm('真的重置【'+data.name+'】的密码吗？', function(index){
                    layer.close(index);
                    //向服务端发送指令
                    $.post("/user/resetUserPwd",{uid:data.id},function(obj){
                        layer.msg(obj.msg);
                    })
                });
            }
        });

        var mainIndex;
        var url;

        //打开添加的弹出层
        function openAddLayer() {
            mainIndex = layer.open({
                type: 1,
                title: '添加用户',
                skin: 'layui-layer-molv', //加上边框
                area: ['800px', '500px'], //宽高
                content: $("#saveOrUpdateDiv"),
                success: function (index) {
                    $("#dataFrm")[0].reset();
                    $(".dtree-select").removeClass("dtree-select-show");//解决弹出层里面的下列树展开的问题

                    //加载最大的排序码
                    $.post("/user/loadUserMaxOrderNum", function (res) {
                        $("#ordernum").val(res.data);
                    })
                }

            })
        };
        //打开修改的弹出层
        function openUpdateLayer(data){
            mainIndex=layer.open({
                type: 1,
                title:'修改用户',
                skin: 'layui-layer-molv', //加上边框
                area: ['800px', '500px'], //宽高
                content: $("#saveOrUpdateDiv"),
                success:function(index){
                    url="/user/updateUserView?uid="+data.id;
                    $("#dataFrm")[0].reset();
                    $.get(url,function(json){
                        var userRes = json.data;
                        $("input[name=id]").val(userRes.id);
                        $("input[name=name]").val(userRes.name);
                        $("input[name=loginname]").val(userRes.loginname);
                        $("input[name=address]").val(userRes.address);
                        $("input[name=ordernum]").val(userRes.ordernum);
                        $(".layui-textarea").text(userRes.remark);
                        initradio('sex', userRes.sex);
                        initradio('available', userRes.available);
                    },'json');
                    $(".dtree-select").removeClass("dtree-select-show");//解决弹出层里面的下列树展开的问题
                    //反选所属部门
                    dtree.dataInit("deptTree", data.deptid+"");
                    dtree.selectVal("deptTree");

                    $.post("/user/loadUserByUserId",{userId:data.mgr},function(res){
                        //反选领导部门
                        dtree.dataInit("leaderDeptTree", res.data.deptid+"");
                        dtree.selectVal("leaderDeptTree");

                        $.post("/user/queryUserByDeptId",{deptid:res.data.deptid},function(res){
                            var domMgr=$("#mgr");
                            var html="<option value=''>请选择领导</option>";
                            $.each(res.data,function(i,item){
                                if(data.mgr==item.id){
                                    html+="<option value="+item.id+" selected='selected'>"+item.name+"</option>";
                                }else{
                                    html+="<option value="+item.id+">"+item.name+"</option>";
                                }
                            });
                            domMgr.html(html);
                            form.render();//重新渲染表单
                        })
                    })

                }

            })
        };
        //
        //监听提交按钮的事件
        form.on("submit(doSubmit)", function (data) {
            var params = $("#dataFrm").serialize();
            var subtype = $(".subType").val();
            if (subtype == "add") {
                url = "/user/addUser";
            } else {
                url = "/user/updateUser";
            }
            //提交 数据
            $.post(url, params, function (obj) {
                if (obj.code == 200) {
                    tableIns.reload();//重载表格
                }
                layer.msg(obj.msg);
                layer.close(mainIndex);
            })
            return false;//阻止同步提交
        });

        //批量删除
        function batchDelete(obj){
            var checkStatus = table.checkStatus('userTable'); //idTest 即为基础参数 id 对应的值
            if(checkStatus.data.length==0){
                layer.msg("请选中要删除的数据行");
            }else{
                layer.confirm('真的删除选中的所有用户么?', function(index){
                    layer.close(index);
                    var params="";
                    $.each(checkStatus.data,function(i,item){
                        if(i==0){
                            params+="ids="+item.id;
                        }else{
                            params+="&ids="+item.id;
                        }
                    });
                    //向服务端发送删除指令
                    $.post("/user/batchDeleteUser",params,function(obj){
                        if(obj.code==200){
                            tableIns.reload();//重载表格
                        }
                        layer.msg(obj.msg);
                    })
                });
            }
        }


        //初始化查询条件的下拉树
        var searchDeptTree = dtree.renderSelect({
            elem: "#searchDeptTree",
            url: "/dept/loadAllDeptTreeJson",
            dataStyle: "layuiStyle",  //使用layui风格的数据格式
            dataFormat: "list",  //配置data的风格为list
            selectTips: "请选择所属部门",
            selectInputName: {
                nodeId: "deptid"//,  //提交到后台的部门ID的key
                // context: "pname"//提交到后台的部门名称
            },
            response: {message: "msg", statusCode: 0} //修改response中返回数据的定义
            //,skin: "layui"
        });
        //
        //查询条件的重置按钮重置下拉树
        $("#searchFrmReset").click(function () {
            searchDeptTree.selectResetVal();
        })

        //添加修改页面所属部门树
        var deptTree=dtree.renderSelect({
            elem: "#deptTree",
            url: "/dept/loadAllDeptTreeJson",
            dataStyle: "layuiStyle",  //使用layui风格的数据格式
            dataFormat: "list",  //配置data的风格为list
            selectTips: "请选择所属部门",
            selectInputName: {
                nodeId: "deptid"//,  //提交到后台的部门ID的key
                // context: "pname"//提交到后台的部门名称
            },
            response:{message:"msg",statusCode:0} //修改response中返回数据的定义
            //,skin: "layui"
        });
        //添加修改页面，。领导部门树
        var leaderDeptTree=dtree.renderSelect({
            elem: "#leaderDeptTree",
            url: "/dept/loadAllDeptTreeJson",
            dataStyle: "layuiStyle",  //使用layui风格的数据格式
            dataFormat: "list",  //配置data的风格为list
            selectTips: "请选择领导部门",
            response:{message:"msg",statusCode:0} //修改response中返回数据的定义
            //,skin: "layui"
        });
        //监听领导部门树的点击事件
        dtree.on("node('leaderDeptTree')" ,function(obj){
            var leaderDeptid=obj.param.nodeId;
            $.post("/user/queryUserByDeptId",{deptid:leaderDeptid},function(res){
                var domMgr=$("#mgr");
                var html="<option value=''>请选择领导</option>";
                $.each(res.data,function(i,item){
                    html+="<option value="+item.id+">"+item.name+"</option>";
                });
                domMgr.html(html);
                form.render();//重新渲染表单
            })
        });

        //查询条件的重置按钮重置下拉树
        $("#searchFrmReset").click(function(){
            searchDeptTree.selectResetVal();
        });

        //打开分配角色的弹出层
        function openSelectUserRoleLayer(data){
            var roleTableIns;
            mainIndex=layer.open({
                type: 1,
                title:'分配【'+data.name+'】角色的权限',
                skin: 'layui-layer-molv', //加上边框
                area: ['800px', '500px'], //宽高
                content: $("#selectUserRoleDiv"),
                btn: ['确认分配', '关闭窗口'],
                yes: function(index, layero){
                    //得到当产有树选中值
                    var checkStatus = table.checkStatus('roleTable'); //idTest 即为基础参数 id 对应的值
                    var roleData=checkStatus.data;
                    var params="userId="+data.id;
                    $.each(roleData,function(i,item){
                        params+="&rids="+item.id;
                    })
                    $.post("/user/saveUserRole",params,function(res){
                        layer.msg(res.msg);
                        window.location.reload();
                    })
                },
                btnAlign: 'c',
                success:function(index){
                    //初始化角色表格的数据
                    roleTableIns=table.render({
                        elem: '#roleTable'
                        ,url:'/role/loadRolesByUserId?userId='+data.id
                        ,cols: [ [
                            {type: 'checkbox', fixed: 'left'}
                            ,{field:'id', title:'ID',align:'center', fixed: 'left'}
                            ,{field:'name', title:'角色标题',align:'center'}
                            ,{field:'remark', title:'角色备注',align:'center'}
                            ,{field:'createtime', title:'创建时间',align:'center'}
                        ] ]
                        ,page: true
                    });
                }

            })
        }


        function exportUser(){
            var checkStatus = table.checkStatus('userTable'); //idTest 即为基础参数 id 对应的值
            var params="";
            if(checkStatus.data.length!=0){
                $.each(checkStatus.data,function(i,item){
                    if(i==0){
                        params+="ids="+item.id;
                    }else{
                        params+="&ids="+item.id;
                    }
                });
            }else{
               layer.msg("请选择导出用户");
               return false;
            }
            //向服务端发送删除指令
            $.get("/user/exportCheck",params,function(res){
                  if(res.code==200){
                    window.location.href = "/user/exportUser?"+params
                  }else{
                      layer.msg("下载失败");
                  }
             });
        }

    });

    function initradio(rName,rValue){
        var rObj = document.getElementsByName(rName);

        for(var i = 0;i < rObj.length;i++){
            if(rObj[i].value == rValue){
                rObj[i].checked =  'checked';
            }
        }
    }
</script>

</body>
</html>